package com.chinda.common.xss;

import cn.hutool.core.util.StrUtil;
import com.chinda.common.exception.RRException;

/**
 * sql过滤
 * @author Wang Chinda
 * @date 2020/8/8
 * @see
 * @since 1.0
 */
@SuppressWarnings("AlibabaClassNamingShouldBeCamel")
public class SQLFilter {

    private SQLFilter() {
        throw new IllegalStateException("Utility class");
    }


    /**
     * SQL注入过滤
     * @param str  待验证的字符串
     */
    public static String sqlInject(String str) {
        if (StrUtil.isBlank(str)) {
            return null;
        }
        //去掉'|"|;|\字符
        str = StrUtil.replace(str, "'", StrUtil.SPACE);
        str = StrUtil.replace(str, "\"", StrUtil.SPACE);
        str = StrUtil.replace(str, ";", StrUtil.SPACE);
        str = StrUtil.replace(str, "\\", StrUtil.SPACE);

        //非法字符
        String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"};

        //判断是否包含非法字符
        if (StrUtil.containsAnyIgnoreCase(str, keywords)) {
            throw new RRException("包含非法字符");
        }
        return str;
    }
}
